package com.ikingtech.framework.sdk.web.support.agent;

import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.common.FrameworkAgentTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class LoadBalanceFrameworkAgent implements FrameworkAgent {

    private final List<FrameworkAgentCaller> callers;

    private final List<FrameworkAgentRunner> runners;

    @Value("${spring.application.name}")
    private String applicationName;

    private Map<FrameworkAgentTypeEnum, FrameworkAgentCaller> callerMap;

    private Map<FrameworkAgentTypeEnum, FrameworkAgentRunner> runnerMap;

    @Override
    public R<Object> execute(FrameworkAgentTypeEnum agentType, Object data) {
        if (!this.callerMap.containsKey(agentType)) {
            return R.failed("agent caller not found.");
        }
        FrameworkAgentCaller caller = this.callerMap.get(agentType);
        if (Tools.Str.equals(this.applicationName, caller.provider())) {
            // 调用方和提供方一致，降级为本地调用
            return this.runnerMap.get(agentType).run(data);
        }
        return caller.call(data);
    }

    public void init() {
        this.callerMap = Tools.Coll.convertMap(this.callers, FrameworkAgentCaller::type);
        this.runnerMap = Tools.Coll.convertMap(this.runners, FrameworkAgentRunner::type);
        FrameworkAgentProxy.accept(this);
    }
}
